<?php
    require_once './Tool/DB/SqlDBManager.class.php';
    $sqlDBManager = new SqlDBManager();

    $Username = $_SESSION['username'];
    $NRIC = $_REQUEST['barcode'];
    $userCenterName = $_SESSION["centreName"];
    $centreName = "";

    $sql = "Select CentreName from centre where CentreId = (SELECT client.CentreId from centre, client WHERE client.NRIC = ? AND centre.CentreId = client.CentreId)";
    $parameters=array($NRIC);
   
    $res=$sqlDBManager->queryRow($sql,$parameters);

    if(!empty($res)){
        $centreName = $res['CentreName'];
    }

    $sql = "Select * from attendancerecord where NRIC= ? AND DATE(SignInTimeStamp)=CURDATE()";
    $parameters=array($NRIC);

    $res=$sqlDBManager->queryRows($sql,$parameters);

    if ($centreName == $userCenterName) {
        if (empty($res)){
            $sql="SELECT  CentreId FROM  client WHERE  NRIC = ?";
            $parameters=array($NRIC);

            $res=$sqlDBManager->queryRow($sql,$parameters);

            if(!empty($res)){
                $centreId=$res['CentreId'];
            }

            $sql="INSERT INTO attendancerecord(NRIC,CentreId,SignInTimeStamp,Status,AuditSignIn) VALUES (?,?,NOW(),?,?)";
            $parameters=array($NRIC,$centreId,'Not Verified',$Username);
            $res=$sqlDBManager->execute_dml($sql,$parameters);         
        }else{
            echo "<font color='red'>Attendance has already been taken.</font>";
        }
    }else{
        echo "<font color='red'>This elderly is not from the ".$userCenterName." Branch.</font>";
    }
    
    //close connection
    $sqlDBManager->close_connect();
?>	